﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TMPro;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.PlayerLoop;
using UnityEngine.Rendering;

public class Card : MonoBehaviour,IPointerEnterHandler,IPointerExitHandler
{
    public ChessSide side;
    // 是否正在动画中
    public bool isAnimating = true;
    // 是否可用,能量够不够
    public bool isAvailable = true;

    [Header("组件")]
    // 血量文本
    public TextMeshPro hpText;
    public TextMeshPro soldierText;
    public BuildingChessDateSO buildingDate;
    public SpriteRenderer cardSprite;
    public SpriteRenderer card;
    public SpriteRenderer bgSprite;
    
    public Sprite bg;
    

    [Header("原始数据")]
    public Vector3 originPosition;
    public Quaternion originRotation;
    public int originLayerOrder;

    private readonly float minX = -0.4f; 
    private readonly float maxX = 0.4f; 
    private readonly float baseY = 1.02f;
    private readonly float objectWidth = 0.1f; 

    public BoxCollider2D boxCollider2D;

    private List<GameObject> resourcePoints = new List<GameObject>();

    


    [ContextMenu("InitCard")]
    public void Init(BuildingChessDateSO buildingChessDate,ChessSide chessSide)
    {
        ClearResoursePoint();
        resourcePoints.Clear();
        //todo:卡牌初始化的时候,side不同初始化方法应该不同
        buildingDate = buildingChessDate;
        side = chessSide;
        if (side == ChessSide.Player1)
        {
            bgSprite.sprite = buildingDate.chessBackgroundSprite;
            cardSprite.sprite = buildingDate.chessSprite;
            card.sprite = buildingDate.cardBackgroundSprite;
            soldierText.text = buildingDate.soldierChessDates.Count.ToString();
            hpText.text = buildingDate.health.ToString();
            SetResourceLayout(buildingDate.resourcesPoint);
        }else if (side == ChessSide.Player2)
        {
            
            card.sprite = bg;
            cardSprite.sprite = null;
            bgSprite.sprite = null;
            soldierText.text = null;
            hpText.text = null;
        }
        
        
        isAvailable = true;
    }

    // 更新位置和旋转
    public void UpdatePositionRotation(Vector3 position, Quaternion rotation)
    {
        // 将传入的位置赋值给originPosition
        originPosition = position;
        // 将传入的旋转赋值给originRotation
        originRotation = rotation;
        // 获取SortingGroup组件的sortingOrder属性，赋值给originLayerOrder
        
        originLayerOrder = GetComponent<SortingGroup>().sortingOrder;
    }

    // 设置资源布局
    public void SetResourceLayout(int amount)
    {
        GameObject go;

        int objectCount = amount;
        // 计算总长度，使其随物体数量增加而增加，但不超过最大总长度
        float totalLength = Mathf.Min(objectCount * objectWidth + (objectCount - 1) * objectWidth, maxX - minX);

        // 计算物体之间的间距
        float spaceBetweenObjects = (totalLength - objectCount * objectWidth) / (objectCount - 1);
        // 如果只有一个物体，直接放置在中间
        if (objectCount == 1)
        {
            go = PoolTool.GetInstance().GetObjectFromPool("ResourcesPoint");
            go.transform.parent = this.transform;
            go.transform.localPosition = new Vector3(0, baseY, 0);
            resourcePoints.Add(go);
            return;
        }

        // 遍历所有物体并设置位置
        for (int i = 0; i < objectCount; i++)
        {
            float xPosition = -totalLength / 2 + objectWidth / 2 + i * (objectWidth + spaceBetweenObjects);
            go = PoolTool.GetInstance().GetObjectFromPool("ResourcesPoint");
            go.transform.parent = this.transform;
            go.transform.localPosition = new Vector3(xPosition, baseY, 0);
            
            resourcePoints.Add(go);
        }
    }

    private void ClearResoursePoint()
    {
        var list = GetComponentsInChildren<ResoursePoint>(true);
        foreach (var item in list)
        {
            item.gameObject.SetActive(false);
        }
    }


    public void UpdateCardState(){
        isAvailable = buildingDate.resourcesPoint <= (side == ChessSide.Player1
            ? PlayerResourcesManager.GetInstance().Player1Resources
            : PlayerResourcesManager.GetInstance().Player2Resources);
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        if(side != ChessSide.Player1)
            return;
        if(Settings.isPlayerTurn == false)
            return;
        if(isAnimating)
            return;
        if(!Settings.canBeUsed)
            return;
        
        transform.position = originPosition + Vector3.right*0.5f;
        boxCollider2D.size += Vector2.right * 0.5f;
        boxCollider2D.offset = Vector2.left * 0.25f;
        transform.rotation = quaternion.identity;
        GetComponent<SortingGroup>().sortingOrder = 100;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        if(side != ChessSide.Player1)
            return;
        if(Settings.isPlayerTurn == false)
            return;
        if(isAnimating)
            return;
        if(!Settings.canBeUsed)
            return;
        
        RestCardTransform();
    }

    public void RestCardTransform()
    {
        transform.SetPositionAndRotation(originPosition, originRotation);
        GetComponent<SortingGroup>().sortingOrder = originLayerOrder;
        boxCollider2D.size -= Vector2.right * 0.5f;
        boxCollider2D.offset = Vector2.zero;
    }

    public async Task UseCardAsync()
    {
        EventCenter.GetInstance().EventTrigger<Card,ChessSide>("DiscardCard",this,side);
        bool isSucceed  = await HandleUseManager.GetInstance().PlacedChessAsync(
            null,buildingDate.canPlacedLattices,buildingDate,
            Settings.canPlaced);
        if(isSucceed)
        {
            TurnBaseManager.GetInstance().Player1TurnEnd();
            return;
        }
        //没有使用成功重新添加卡牌,加入手牌,弃牌堆去除,实例化
        EventCenter.GetInstance().EventTrigger<Card,ChessSide>("FailedToUse",this,side);
    }

    public void DiscardResourcesPoint()
    {
        foreach (var resourcePoint in resourcePoints)
        {
            resourcePoint.transform.SetParent(PoolTool.GetInstance().transform);
            PoolTool.GetInstance().ReleaseObjectToPool("ResourcesPoint",resourcePoint);
        }
        resourcePoints.Clear();
    }

    public void UseCard(Vector2Int position)
    {
        EventCenter.GetInstance().EventTrigger<Card,ChessSide>("DiscardCard",this,side);
        EventCenter.GetInstance().EventTrigger("ReduceResources", side, buildingDate.resourcesPoint);
        ChessManager.GetInstance().InitChess(buildingDate,position,ChessSide.Player2);
    }
    
    
}
